'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  List,
  Tag,
  Progress,
  Typography,
  Avatar,
  Divider,
  Modal
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { UserOutlined, FileTextOutlined, CommentOutlined, LikeOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { commonService } from '@/service/common.service';
import { formatTimeDisplay } from '@/util/util';
const { Title, Text, Paragraph } = Typography;

// 仪表盘组件
const Dashboard: React.FC = () => {
  // 系统统计数据
  const [statistics, setStatistics] = useState({
    users: 0,
    articles: 0,
    comments: 0,
    likes: 0
  });

  // 近期活动日志
  const [activityLogs, setActivityLogs] = useState([
    {
      id: 1,
      uid: 0,
      username: 'admin',
      logcontent: '发布了新文章',
      type: 0,
      createdAt: '2分钟前',
      avatar: 'A'
    },
  ]);

  // 热门文章排行
  const [hotArticles, setHotArticles] = useState([]);

  // 系统状态
  const [systemStatus, setSystemStatus] = useState({
    cpuUsage: 35,
    memoryUsage: 62,
    processMemMB: 150,
    uptime: '12天3小时'
  });

  // 初始化数据加载
  useEffect(() => {
    const loadData = async () => {
      try {

        // 系统统计数据
        const statsResponse = await commonService.getSystemStats();
        // console.log("状态仪表盘数据2:  " , statsResponse);
        setStatistics({
          users: statsResponse.userStats.total,
          articles: statsResponse.articleStats.total,
          comments: statsResponse.commentCount,
          likes: statsResponse.likeCount
        });
        
        // 最近活动日志
        // const logsResponse = await commonService.getLatestLogs();
        // console.log("最新日志数据:  " , logsResponse);
        // setActivityLogs(logsResponse);

        // 热门文章排行
        const articlesResponse = await commonService.getHotArticles();
        setHotArticles(articlesResponse);
        
      } catch (error) {
        console.error('加载仪表盘数据失败:', error);
      }
    };

    loadData();
    
    
    // 设置定时更新系统状态（每5秒更新一次）
    const statusInterval = setInterval(async () => {
      try {
        const statusResponse = await commonService.getSystemStatus();
        setSystemStatus(statusResponse);
      } catch (error) {
        console.error('更新系统状态失败:', error);
      }
    }, 10000);

    return () => clearInterval(statusInterval);
  }, []);

  // 热门文章表格列配置
  const articleColumns: ColumnsType<any> = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 60,
      render: (text: string, record: any, index: number) => (
        <span style={{ fontWeight: 'bold', color: index < 3 ? '#1890ff' : '#666' }}>
          {index + 1}
        </span>
      )
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string) => (
        <a href={`http://localhost:3000/article/${text}`} target="_blank" rel="noopener noreferrer">
          {text}
        </a>
      )
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 100
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 100,
      align: 'right',
      render: (count: number) => <Text type="success">{count}</Text>
    },
    {
      title: '点赞数',
      dataIndex: 'likeCount',
      key: 'likeCount',
      width: 100,
      align: 'right',
      render: (count: number) => <Text type="warning">{count}</Text>
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>仪表盘</Title>
      
      {/* 系统统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card bordered={false}>
            <Statistic
              title="用户总数"
              value={statistics.users}
              prefix={<UserOutlined />}
              suffix="人"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false}>
            <Statistic
              title="文章总数"
              value={statistics.articles}
              prefix={<FileTextOutlined />}
              suffix="篇"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false}>
            <Statistic
              title="评论总数"
              value={statistics.comments}
              prefix={<CommentOutlined />}
              suffix="条"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card bordered={false}>
            <Statistic
              title="点赞总数"
              value={statistics.likes}
              prefix={<LikeOutlined />}
              suffix="次"
              valueStyle={{ color: '#fa541c' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 中间内容区域 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 系统状态监控 */}
        <Col span={8}>
          <Card title="系统状态监控" bordered={true}>
            <div style={{ marginBottom: '20px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <Text>CPU 使用率</Text>
              </div>
              <Progress percent={systemStatus.cpuUsage} status="active" strokeColor="#1890ff" />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <Text>内存使用率</Text>
              </div>
              <Progress percent={systemStatus.memoryUsage} status="active" strokeColor="#52c41a" />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <Text>服务器程序内存占用</Text>
                <Text>{systemStatus.processMemMB} MB</Text>
              </div>
            </div>
            
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Text>系统运行时间</Text>
                <Text type="secondary">{systemStatus.uptime}</Text>
              </div>
            </div>
          </Card>
        </Col>
        
        {/* 近期活动日志 */}
        <Col span={8}>
          <Card title="近期活动日志" bordered={true}>
            <List
              itemLayout="horizontal"
              dataSource={activityLogs}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar>{item.username}</Avatar>}
                    title={
                      <div>
                        <Text strong>{item.username}</Text>
                        <Text> {item.logcontent} </Text>
                      </div>
                    }
                    description={<Text type="secondary" className="ant-list-item-meta-description">
                      <ClockCircleOutlined style={{ marginRight: '5px' }} />
                      { formatTimeDisplay(item.createdAt)}
                    </Text>}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
        
        {/* 热门文章排行 */}
        <Col span={8}>
          <Card title="热门文章排行" bordered={true}>
            <Table
              columns={articleColumns}
              dataSource={hotArticles.map((article, index) => ({ ...article, rank: index + 1 }))}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      {/* 底部数据卡片 */}
      <Row gutter={16}>
        {/* 今日数据概览 */}
        <Col span={12}>
          <Card title="今日数据概览" bordered={true}>
            <Row gutter={16}>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <Statistic
                    value={67}
                    title="新增用户"
                    valueStyle={{ color: '#3f8600' }}
                  />
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <Statistic
                    value={12}
                    title="新增文章"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <Statistic
                    value={253}
                    title="新增评论"
                    valueStyle={{ color: '#722ed1' }}
                  />
                </div>
              </Col>
            </Row>
            
            <Divider style={{ margin: '16px 0' }} />
            
            <div>
              <Title level={5}>内容分布</Title>
              <Row gutter={16}>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>已发布</Text>
                      <Text>75%</Text>
                    </div>
                    <Progress percent={75} status="active" strokeColor="#52c41a" />
                  </div>
                </Col>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>待审核</Text>
                      <Text>20%</Text>
                    </div>
                    <Progress percent={20} status="active" strokeColor="#faad14" />
                  </div>
                </Col>
              </Row>
              <Row gutter={16} style={{ marginTop: '16px' }}>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>草稿</Text>
                      <Text>3%</Text>
                    </div>
                    <Progress percent={3} status="active" strokeColor="#1890ff" />
                  </div>
                </Col>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>已拒绝</Text>
                      <Text>2%</Text>
                    </div>
                    <Progress percent={2} status="active" strokeColor="#ff4d4f" />
                  </div>
                </Col>
              </Row>
            </div>
          </Card>
        </Col>
        
        {/* 用户活跃度统计 */}
        <Col span={12}>
          <Card title="用户活跃度统计" bordered={true}>
            <div style={{ marginBottom: '24px' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '16px', marginBottom: '16px' }}>
                <Tag color="success">活跃用户: 236人</Tag>
                <Tag color="warning">新用户: 67人</Tag>
                <Tag color="default">潜水用户: 423人</Tag>
                <Tag color="error">禁用用户: 12人</Tag>
              </div>
              
              <Title level={5}>用户角色分布</Title>
              <Row gutter={16}>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>普通用户</Text>
                      <Text>85%</Text>
                    </div>
                    <Progress percent={85} status="active" strokeColor="#1890ff" />
                  </div>
                </Col>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>编辑用户</Text>
                      <Text>10%</Text>
                    </div>
                    <Progress percent={10} status="active" strokeColor="#722ed1" />
                  </div>
                </Col>
              </Row>
              <Row gutter={16} style={{ marginTop: '16px' }}>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>管理员</Text>
                      <Text>4%</Text>
                    </div>
                    <Progress percent={4} status="active" strokeColor="#fa8c16" />
                  </div>
                </Col>
                <Col span={12}>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                      <Text>超级管理员</Text>
                      <Text>1%</Text>
                    </div>
                    <Progress percent={1} status="active" strokeColor="#ff4d4f" />
                  </div>
                </Col>
              </Row>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
